﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml;
using ButsaScraperLib;

namespace ForecastManager.Dialogs
{
	/// <summary>
	/// Interaction logic for LoadResultDialog.xaml
	/// </summary>
	public partial class LoadResultDialog : Window
	{
		private Snapshot _snapshot;

		private bool _resultsAreLoaded;

		public LoadResultDialog(Snapshot snapshot)
		{
			InitializeComponent();
			_snapshot = snapshot;
		}

		public Snapshot GetSnapshot()
		{
			return _snapshot;
		}

		private void LoadButtonClick(object sender, RoutedEventArgs e)
		{
			if (!_resultsAreLoaded)
			{
				LoadButton.IsEnabled = false;
				Thread thread = new Thread(ReadResults) {IsBackground = true};
				thread.Start();
			}
			else
			{
				DialogResult = true;
			}
		}

		private void ReadResults()
		{
			foreach (ForecastPairRef forecastPair in _snapshot.ForecastPairs)
			{
				Score score = ButsaManager.Instance.GetMatchResultForTeams(forecastPair.HomeTeamId.ToString(),
				                                                           forecastPair.GuestTeamId.ToString());

				string homeTeamName = _snapshot.Teams.First(item => item.TeamId == forecastPair.HomeTeamId.ToString()).TeamName;
				string guestTeamName = _snapshot.Teams.First(item => item.TeamId == forecastPair.GuestTeamId.ToString()).TeamName;

				LogMessage(String.Format(String.Format("{0} ({1}) - {2} - {3} ({4})\r\n", homeTeamName, forecastPair.HomeTeamId,
				                                       score, guestTeamName, forecastPair.GuestTeamId)));

				forecastPair.HomeTeamGoals = score.HomeTeamGoals;
				forecastPair.GuestTeamGoals = score.GuestTeamGoals;
			}
			_resultsAreLoaded = true;
			LoadButton.Dispatcher.Invoke(new Action(() =>
			                                        	{
			                                        		LoadButton.IsEnabled = true;
			                                        		LoadButton.Content = "Закрыть";
			                                        	}), new object[] {});
		}

		private void LogMessage(string message)
		{
			if (LogTextBox.Dispatcher.CheckAccess())
			{
				LogTextBox.Text = message + "\r\n" + LogTextBox.Text;
			}
			else
			{
				LogTextBox.Dispatcher.Invoke(new Action(() => LogMessage(message)), new object[] { });
			}
		}
	}
}
